﻿using Microsoft.Extensions.Configuration;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace Microsoft.Configuration
{
    /// <summary>
    /// 针对<see cref="IConfiguration"/>进行扩展
    /// </summary>
    public static class ConfigurationExtensions
    {
        /// <summary>
        /// 更新配置中的数据并进行持久化保存
        /// </summary>
        /// <param name="configuration"><inheritdoc cref="IConfiguration" path="/summary"/></param>
        /// <param name="key">要查找的键名</param>
        /// <param name="value">修改后的值</param>
        /// <param name="path">配置文件所在路径，默认是：<see langword="bin/debug/apssetings.json"/></param>
        /// <returns></returns>
        public static IConfiguration Set(this IConfiguration configuration, string key, object value, string path = "appsettings.json")
        {
            JObject jObject = JObject.Parse(File.ReadAllText(path, Encoding.UTF8));
            string contents;
            if (string.IsNullOrEmpty(key))
            {
                contents = JToken.FromObject(value).ToString();
            }
            else
            {
                string[] array = key.Split(':');
                JToken jToken = jObject;
                for (int i = 0; i < array.Length - 1; i++)
                {
                    if (jToken[array[i]] == null)
                    {
                        jToken[array[i]] = JToken.FromObject(new object());
                    }

                    jToken = jToken[array[i]];
                }

                jToken[array[array.Length - 1]] = JToken.FromObject(value);
                contents = jObject.ToString();
            }

            lock (typeof(object))
            {
                File.WriteAllText(path, contents, Encoding.UTF8);
            }

            return configuration;
        }
    }
}
